/*
 * 
 * Implementa a classe responsavel pelo estado do login
 * na memória de sessão atual.
 * 
 */

package br.unirio.bsi.dsw.AuctionSite.action;

import java.util.Date;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.*;

import br.unirio.bsi.dsw.AuctionSite.model.dao.GenericDAO;

import br.unirio.bsi.dsw.AuctionSite.beans.loginForm;
import br.unirio.bsi.dsw.AuctionSite.beans.util.copyBean;


public class loginAction extends Action 
{
  private final static String SUCCESS = "success";
  private final static String FAILURE = "failure";
  
  @Override
  public ActionForward execute(ActionMapping mapping, 
                               ActionForm form,
                               HttpServletRequest request, 
                               HttpServletResponse response) throws Exception 
  {   
    // cria a entidade do modelo com as suas especificidades (gerenciador)
    loginForm lf = new loginForm();
    
    copyBean.fromActionForm(lf, form);
                          
    // pega instancia do DAO
    GenericDAO gD = GenericDAO.getInstance( getResources(request).getMessage("DB_NAME") );

    // get user from the database
    if( gD.retrieve( lf ) == null ) 
    {
      // if no user was retrieved
      ActionErrors errors = new ActionErrors();
      errors.add("error.wrong.login", new ActionMessage("error.wrong.login") );
      saveErrors(request, errors); 
      
      return mapping.findForward(FAILURE);
    }
    
    // performs
    doLogon( lf, request );

    return mapping.findForward(SUCCESS);
  }
  
  public static void doLogon( loginForm lf, HttpServletRequest request )
  {    
    // get session
    HttpSession session = request.getSession();
    
    // define usuario logado
    lf.setLogged( true );

    // define a hora do recente logon
    lf.setUltimoLogin( new Date() );

    // coloca o usuario na memória de sessão
    session.setAttribute("loginForm", lf);
  }
}
